﻿using Cognex.VisionPro;
using Cognex.VisionPro.Implementation;
using Cognex.VisionPro.ToolBlock;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows;
using YJYpublicClass;
using YJYpublicClass.DataStruct;

namespace YJYpublicClass.Model
{
    public class ModelCaozuo
    {

        //一些视觉操作也可以在这里完成
        // public CogAcqFifoTool FifoAcq_tool = null;
        //专门处理模型操作的
        public CustomModel modelone = new CustomModel();
        public ICogRecord disprecord_相机1 = null;
        public ICogRecord disprecord_相机2 = null;
        public ICogRecord disprecord_相机3 = null;
        //   public List<ChazhenY_C> Chazhenssend = new List<ChazhenY_C>();
        //定义3个相机，直接由设置成外部
        // public CogToolBlock _B角度1测量工具 = new CogToolBlock(); //要得到x，y，r，不管用什么方法
        public HKCamera2 Camera1;
        public HKCamera2 Camera2;
        public HKCamera2 Camera3;

        public string _工程路径 = "";

        //记录量角度
        public double CCD2R1 = 0;
        public double CCD2R2 = 0;
        public double devCCD2R = 0;
        public Action _配置完成事件 = null;
        //保存
        public ResultFunc Savemode(string path, CustomModel model)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, model);
                stream.Close();
                return new ResultFunc(Funstate.OK, "");
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }
        //加载
        public ResultFunc Loadmode(string path, out CustomModel model)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
                model = (CustomModel)formatter.Deserialize(stream);
                stream.Close();
                //模块赋值
                ResultFunc reslut = model.init();
                if (reslut.State == Funstate.OK)
                {
                    return new ResultFunc(Funstate.OK, "");
                }
                else
                {
                    return new ResultFunc(Funstate.异常, reslut.mes);
                }
            }
            catch (Exception ex)
            {
                model = new CustomModel();
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }

        public void setconfig()
        {
            Frm_模型操作 tempwindow = new Frm_模型操作(this);
            tempwindow.Show();
        }

        #region 引导流程



        public int _相机1取图标志 = 0;
        public int _相机2取图标志 = 0;
        public int _相机3取图标志 = 0;
        private void _相机1取图标志触发事件()
        {
            _相机1取图标志 =1;
        }
        private void _相机2取图标志触发事件()
        {
            _相机2取图标志 =1;
        }
        private void _相机3取图标志触发事件()
        {
            _相机3取图标志 =1;
        }
        public ResultFunc _相机1取图操作()
        {
            try
            {
                if (Camera1==null)
                {
                    return new ResultFunc(Funstate.异常, "相机未注册");
                }
                if (Camera1.CamreOpenFlag!=1)
                {
                    return new ResultFunc(Funstate.异常, "相机未打开");
                }
                Camera1._取图事件-=_相机1取图标志触发事件;
                Camera1._取图事件+=_相机1取图标志触发事件;
                int step = 0;
                ResultFunc result = new ResultFunc();
                Stopwatch t1 = new Stopwatch();         
                while (true)
                {
                    switch (step)
                    {
                        case 0:
                            if (!Camera1.SoftTrige())
                            {
                                return new ResultFunc(Funstate.异常, "触发失败");
                            }
                            _相机1取图标志=0;
                            step =1;
                            t1.Restart();
                            break;
                        case 1:
                            //
                            if (_相机1取图标志!=1)
                            {
                                if (t1.ElapsedMilliseconds>1000)
                                {
                                    t1.Stop();
                               
                                    return new ResultFunc(Funstate.异常, "取图超时");
                                }

                            }
                            else
                            {
                                //显示出来
                                disprecord_相机1=  CreateDisplayRecord(Camera1.OutVisionImage);
                                //并把图像输入给
                                _设置检测1输入图像(Camera1.OutVisionImage);
                                return new ResultFunc();
                            }
                            break;
                    }

                }

              
            }
            catch (Exception ex)
            {
                Camera1._取图事件-=_相机1取图标志触发事件;
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
            finally
            {
                //一次调用一次绑定
                Camera1._取图事件-=_相机1取图标志触发事件;
            }
        }
        public ResultFunc _相机2取图操作()
        {
            try
            {
                if (Camera2==null)
                {
                    return new ResultFunc(Funstate.异常, "相机未注册");
                }
                if (Camera2.CamreOpenFlag!=1)
                {
                    return new ResultFunc(Funstate.异常, "相机未打开");
                }
                Camera2._取图事件-=_相机2取图标志触发事件;
                Camera2._取图事件+=_相机2取图标志触发事件;
                int step = 0;
                ResultFunc result = new ResultFunc();
                Stopwatch t1 = new Stopwatch();
                while (true)
                {
                    switch (step)
                    {
                        case 0:
                            if (!Camera2.SoftTrige())
                            {
                                return new ResultFunc(Funstate.异常, "触发失败");
                            }
                            _相机2取图标志=0;
                            step =1;
                            t1.Restart();
                            break;
                        case 1:
                            //
                            if (_相机2取图标志!=1)
                            {
                                if (t1.ElapsedMilliseconds>1000)
                                {
                                    t1.Stop();
                                    return new ResultFunc(Funstate.异常, "取图超时");
                                }

                            }
                            else
                            {
                                //显示出来
                                disprecord_相机2= CreateDisplayRecord(Camera2.OutVisionImage);
                                //并把图像输入给
                                _设置检测2输入图像((Cognex.VisionPro.CogImage8Grey)Camera2.OutVisionImage);
                                return new ResultFunc();
                            }
                            break;
                    }
                }

            }
            catch (Exception ex)
            {

                return new ResultFunc(Funstate.异常, ex.ToString());
            }
            finally
            {
                Camera2._取图事件-=_相机2取图标志触发事件;
            }
        }
        public ResultFunc _相机3取图操作()
        {
            try
            {
                if (Camera3==null)
                {
                    return new ResultFunc(Funstate.异常, "相机未注册");
                }
                if (Camera3.CamreOpenFlag!=1)
                {
                    return new ResultFunc(Funstate.异常, "相机未打开");
                }
                Camera3._取图事件-=_相机3取图标志触发事件;
                Camera3._取图事件+=_相机3取图标志触发事件;
                int step = 0;
                ResultFunc result = new ResultFunc();
                Stopwatch t1 = new Stopwatch();
                while (true)
                {
                    switch (step)
                    {
                        case 0:
                            if (!Camera3.SoftTrige())
                            {
                                return new ResultFunc(Funstate.异常, "触发失败");
                            }
                            _相机3取图标志=0;
                            step =1;
                            t1.Restart();
                            break;
                        case 1:
                            //
                            if (_相机3取图标志!=1)
                            {
                                if (t1.ElapsedMilliseconds>1000)
                                {
                                    t1.Stop();
                                    return new ResultFunc(Funstate.异常, "取图超时");
                                }

                            }
                            else
                            {
                                //显示出来
                                disprecord_相机3= CreateDisplayRecord(Camera3.OutVisionImage);
                                //并把图像输入给
                                _设置检测3输入图像((Cognex.VisionPro.CogImage8Grey)Camera3.OutVisionImage);
                                return new ResultFunc();
                            }
                            break;
                    }

                }

            }
            catch (Exception ex)
            {

                return new ResultFunc(Funstate.异常, ex.ToString());
            }
            finally
            {
                Camera3._取图事件-=_相机3取图标志触发事件;
            }
        }
        public CogRecord CreateDisplayRecord(Cognex.VisionPro.ICogImage image)
        {
            return new CogRecord("InputImage",
                typeof(Cognex.VisionPro.CogImage8Grey),
                Cognex.VisionPro.CogRecordUsageConstants.Input, false, image, "InputImage");

        }

        //复检部分
        #endregion 引导流程

        #region CCD流程
        public ResultFunc _设置检测1输入图像(ICogImage InputImage)
        {
            int OKNG = 0;
            try
            {

                ResultFunc result = new ResultFunc();
                modelone.CCD1vppblock.Inputs["InputImage"].Value = InputImage as CogImage8Grey;
                return result;
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }
        public ResultFunc _设置检测2输入图像(ICogImage InputImage)
        {
            int OKNG = 0;
            try
            {

                ResultFunc result = new ResultFunc();
                modelone.CCD2vppblock.Inputs["inputImage"].Value = InputImage as CogImage8Grey;
                return result;
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }
        public ResultFunc _设置检测3输入图像(ICogImage InputImage)
        {
            int OKNG = 0;
            try
            {

                ResultFunc result = new ResultFunc();
                modelone.CCD3vppblock.Inputs["inputImage"].Value = InputImage as CogImage8Grey;
                return result;
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }
        //这个初始就是单纯的
        public ResultFunc _相机1角度获取(string type, out double R)
        {
            R = 0;
            int OKNG = 0;
            try
            {
                CogToolBlock tempBlock = null;
                switch (type)
                {
                    case "端盖":
                        tempBlock =modelone.CCD1vppblock.Tools["端盖测量"] as CogToolBlock;
                        break;
                    case "中节":
                        tempBlock =modelone.CCD1vppblock.Tools["中结测量"] as CogToolBlock;
                        break;
                    case "轴盖":
                        tempBlock =modelone.CCD1vppblock.Tools["轴盖测量"] as CogToolBlock;
                        break;
                }
                if (tempBlock==null)
                {
                    return new ResultFunc(Funstate.异常, "未定义块");
                }
                ResultFunc result = new ResultFunc();
                tempBlock.Run();
                if (tempBlock.RunStatus.Result == CogToolResultConstants.Accept)
                {

                    R = (double)tempBlock.Outputs["R"].Value;
                    // 弧度转角度
                    R = NormalizeAngle(R);
                    // OKNG = (int)tempBlock.Outputs["OKNG"].Value;
                    result.mes = result.mes + "完成," + "角度" + R.ToString();
                    //if (OKNG==0)
                    //{
                    //    result.State = Funstate.异常;
                    //    result.mes = result.mes + "完成," + "角度" + R.ToString()+"针丝检测异常";
                    //}
                    //else
                    //{
                    //    result.mes = result.mes + "完成," + "角度" + R.ToString();
                    //}

                }
                else
                {
                    result.State = Funstate.异常;
                    result.mes = result.mes + tempBlock.RunStatus.Message;
                }
                disprecord_相机1 = tempBlock.CreateLastRunRecord().SubRecords[0];
                return result;
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }
        public ResultFunc _相机2角度获取(string type, out double R)
        {
            R = 0;
            int OKNG = 0;
            try
            {
                CogToolBlock tempBlock = null;
                switch (type)
                {
                    case "轴盖":
                        tempBlock =modelone.CCD2vppblock.Tools["轴盖测量"] as CogToolBlock;
                        break;
                    case "中节":
                        tempBlock =modelone.CCD2vppblock.Tools["中结测量"] as CogToolBlock;
                        break;
                    case "端盖":
                        //tempBlock =modelone.CCD2vppblock.Tools["尾结测量"] as CogToolBlock;
                        break;
                }
                if (tempBlock==null)
                {
                    return new ResultFunc(Funstate.异常, "未定义块");
                }
                ResultFunc result = new ResultFunc();
                tempBlock.Run();
                if (tempBlock.RunStatus.Result == CogToolResultConstants.Accept)
                {

                    R = (double)tempBlock.Outputs["R"].Value;
                    R = NormalizeAngle(R);
                    OKNG = (int)tempBlock.Outputs["OKNG"].Value;
                    if (OKNG==0)
                    {
                        result.State = Funstate.异常;
                        result.mes = result.mes + "完成," + "角度" + R.ToString()+"针丝检测异常";
                    }
                    else
                    {
                        result.mes = result.mes + "完成," + "角度" + R.ToString();
                    }

                }
                else
                {
                    result.State = Funstate.异常;
                    result.mes = result.mes + tempBlock.RunStatus.Message;
                }
                disprecord_相机1 = tempBlock.CreateLastRunRecord().SubRecords[0];
                return result;
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }

        public ResultFunc _相机3高度获取(string type, out double R)
        {
            R = 0;
            int OKNG = 0;
            try
            {
               
                CogToolBlock tempBlock = null;
                switch (type)
                {
                    case "轴盖":
                        //tempBlock =modelone.CCD3vppblock.Tools["端盖测量"] as CogToolBlock;
                        break;
                    case "中节":
                        tempBlock =modelone.CCD3vppblock.Tools["中结测量"] as CogToolBlock;
                        break;
                    case "端盖":
                        tempBlock =modelone.CCD3vppblock.Tools["端盖测量"] as CogToolBlock;
                        break;
                }
                if (tempBlock==null)
                {
                    return new ResultFunc(Funstate.异常, "未定义块");
                }
                ResultFunc result = new ResultFunc();
                tempBlock.Run();
                if (modelone.CCD3vppblock.RunStatus.Result == CogToolResultConstants.Accept)
                {

                    R = (double)tempBlock.Outputs["H"].Value;
                    OKNG = (int)tempBlock.Outputs["OKNG"].Value;
                    if (OKNG==0)
                    {
                        result.State = Funstate.异常;
                        result.mes = result.mes + "完成," + "高度" + R.ToString()+"检测异常";
                    }
                    else
                    {
                        result.mes = result.mes + "完成," + "高度" + R.ToString();
                    }

                }
                else
                {
                    result.State = Funstate.异常;
                    result.mes = result.mes + tempBlock.RunStatus.Message;
                }
                disprecord_相机3 = tempBlock.CreateLastRunRecord().SubRecords[0];
                return result;
            }
            catch (Exception ex)
            {
                return new ResultFunc(Funstate.异常, ex.ToString());
            }
        }


        #endregion CCD流程

        public double NormalizeAngle(double radians)
        {
            double degrees = CogMisc.RadToDeg(radians);
            return (degrees % 360 + 360) % 360;
        }

    }
}
